<script lang="ts" setup>
import { onMounted, PropType, reactive } from 'vue'
import { Command } from '@/commands/command.ts'
import qrcode from 'qrcode'
import { RandStrCommand } from '@/commands/commands/rand_str.ts'
import { writeBinaryFile } from '@tauri-apps/api/fs'
import { downloadDir } from '@tauri-apps/api/path'
import { use_global_state } from '@/state/pinia.ts'
import { dbus } from '@/dbus/dbus.ts'

const props = defineProps({
    command: { required: true, type: Object as PropType<Command> },
})

const global_state = use_global_state()
const state = reactive<{ show: boolean }>({ show: false })

onMounted(async () => {
    props
        .command!.execute()
        .finally(async () => {
            await show()
        })
        .finally(async () => {
            dbus.emit('scroll-to-bottom')
        })
})

async function show(): Promise<void> {
    if (props.command!.success && !props.command!.is_history) {
        state.show = true
        global_state.set_allow_close_window(false)
    }

    setTimeout(async () => {
        await qrcode.toCanvas(document.getElementById('canvas'), props.command!.output, { width: 450, errorCorrectionLevel: 'L', margin: 2 })
    }, 300)
}

async function download_qrcode(): Promise<void> {
    const canvas = document.getElementById('canvas') as HTMLCanvasElement

    const rand_str = RandStrCommand.new('randstr -n 32')
    await rand_str.execute()

    canvas.toBlob(async (blob) => {
        writeBinaryFile((await downloadDir()) + rand_str.output + '.png', await blob!.arrayBuffer()).finally(() => {
            window.Message.success('二维码已保存到下载目录')
        })
    })
}

async function close(show: boolean): Promise<void> {
    if (!show) {
        state.show = false
        setTimeout(async () => {
            global_state.set_allow_close_window(true)
        }, 500)
    }
}
</script>

<template>
    <n-space :size="3" :wrap-item="false" align="center">
        <n-space :wrap-item="false" align="center" class="session-message">
            <div>{{ props.command!.success ? '点击下方查看按钮显示二维码' : props.command!.output }}</div>
        </n-space>
        <n-space :wrap="false" :wrap-item="false" align="center">
            <n-text :disabled="!props.command!.success" class="desc-button pointer" type="info" @click="show">查看</n-text>
        </n-space>
        <n-modal :show="state.show" transform-origin="center" @update:show="close">
            <n-space :wrap="false" :wrap-item="false" align="center" class="qrcode-wrap" justify="center" vertical>
                <canvas id="canvas" class="qrcode"></canvas>
                <n-button class="max-width" size="small" type="info" @click="download_qrcode">保存二维码</n-button>
            </n-space>
        </n-modal>
    </n-space>
</template>

<style lang="scss" scoped>
.qrcode-wrap {
    background-color: #ffffff;
    padding: 15px;
}

.qrcode {
    width: 450px;
    height: 450px;
    background-color: #ffffff;
}
</style>
